<?php

namespace app\index\service;

use app\common\model\Trade;
use app\common\service\GatewayClientServer;
use app\index\dao\TradeDao;
use app\index\model\UM as UM;
use app\index\traits\PaymentTrait;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class OrderCancelService
 * @package app\index\service
 */
class OrderCancelService
{
    use PaymentTrait;

    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return Trade
     */
    public function modify(UM $user, int $id, array $params): Trade
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = Trade::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该订单不存在或已被删除');
        }

        if ($user->id != $record->memberId) {
            throw new ValidateException('您不能取消该订单');
        }

        // 支付状态
        if ($record->payStatus != Trade::UNPAID) {
            if ($record->payStatus == Trade::PAID) {
                throw new ValidateException('该订单已经支付，不能取消');
            }
            if ($record->payStatus == Trade::CANCELLED) {
                throw new ValidateException('该订单已经取消');
            }
            throw new ValidateException('该订单不能取消');
        }

        // 取消支付预下单
        $payment = $this->getPayment($record->payMethod);
        if ($payment) {
            $payment->cancelPay($record);
        }

        // 取消订单
        $record->payStatus = Trade::CANCELLED;
        $record->save();

        // 订单取消后，更新红点
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($record->memberId, json_encode($data));

        return $record;
    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
